<template>
  <div class="mg16 flex">
    <left :setpData="setpData" :content="contentLeft"></left>
    <div class="apply_right" v-if="!isStep2">
      <steps-demo :stepsObj="stepsObj"></steps-demo>
      <div class="right_form">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="会议名称" prop="title">
            <el-input
              v-model="ruleForm.title"
              placeholder="请输入会议名称"
              class="wid450"
            ></el-input>
          </el-form-item>
          <el-form-item label="会议时间" prop="StartTime">
            <el-date-picker
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="ruleForm.StartTime"
              class="wid200"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="产品分类" prop="immsortThree">
            <el-cascader
              v-if="showvideo"
              ref="areaCascader"
              v-model="ProductClassification"
              class="formWidthdpl300"
              :props="CPprops"
              @change="changeImmsort"
            />
          </el-form-item>
          <el-form-item label="领域分类" prop="imIndustrytwo">
            <el-cascader
              v-if="showvideo"
              v-model="DomainClassification"
              ref="areaCascader2"
              class="formWidthdpl300"
              :props="props2"
              @change="changeImIndustry"
            />
          </el-form-item>
          <el-form-item label="内容分类" prop="contentType">
            <el-select
              class="formWidthdpl300"
              v-model="ruleForm.contentType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in contentTypeData"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="大会介绍" prop="contentHtml">
            <div style="width: 60%" v-if="showvideo">
              <Ueditor
                ref="ue"
                :value="defaultMSGPc"
                style="width: 100%"
                :ueditor-config="ueditorConfig"
                @ready="editorReady"
              />
            </div>
            <!-- <p class="hint">
          1、请不要在详细描述中含有联系方式，如电话，QQ，手机等联系方式，网站提供统一的联系方式入口；
        </p>
        <p class="hint">
          2、上传图片前请确保图片来源合规，注意避免图片侵权风险；
        </p> -->
          </el-form-item>
        </el-form>
        <div class="right_btm">
          <el-button @click="saveDrafts()">保存草稿箱</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >下一步</el-button
          >
        </div>
      </div>
    </div>
    <div class="apply_right" v-if="isStep2">
      <steps-twos :isStep2="isStep2" :firstFrom="firstFrom" @isleave="isleave"></steps-twos>
    </div>
  </div>
</template>

<script>
import Ueditor from "@/components/UEditor";
import left from "../components/left.vue";
import stepsDemo from "../components/Steps.vue";
import stepsTwos from "./step2.vue";
import axios from "axios";
import Cookies from 'js-cookie'
import api from "@/api/index";
import { changeDateFormat7 } from "@/utils/commin";
export default {
  components: {
    left,
    stepsDemo,
    Ueditor,
    stepsTwos,
  },
  data() {
    return {
      setpData: {
        step: 1,
        stepExamineOneStatus: 2,
        stepExaminetwoStatus: 1,
      },
      firstFrom: {},
      showvideo: true,
      stepsObj: {
        list: ["填写会议信息", "进行会议设置", "会议预约审核"],
        nums: 1,
      },
      isCanleave: false, // 是否可以离开当前页面
      isStep2: false,
      ProductClassification: [],
      DomainClassification: [],
      CPprops: {
        lazy: true,
        lazyLoad: this.getLazyload, // 产品分类
      },
      props2: {
        lazy: true,
        lazyLoad: this.getLazyload2, // 领域分类
      },
      ruleForm: {
        title: "",
        //内容分类
        contentType: "",
        //开始时间
        StartTime: "",
        //大会简介
        contentHtml: "",
        //行业产品线
        imIndustryone: "",
        imIndustryoneName: "",
        imIndustrytwo: "",
        imIndustrytwoName: "",
        immsortOne: "",
        immsortOneName: "",
        immsortThree: "",
        immsortThreeName: "",
        immsortTwo: "",
        immsortTwoName: "",
      },
      contentTypeData: [
        { name: "原理知识", value: "1" },
        { name: "方法应用", value: "2" },
        { name: "维护维修", value: "3" },
        { name: "数据处理", value: "4" },
        { name: "产品介绍", value: "5" },
      ],
      defaultMSGPc: "",
      instance: "",
      ueditorConfig: {
        toolbars: [
          ['fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'pasteplain', '|', 'forecolor', 'backcolor', 'selectall', '|',
            'fontfamily', 'fontsize', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'link', 'unlink', '|',
            'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify',
            '|',
            'insertimage', 'attachment', 'spechars', 'insertvideo', 'word2html', 'insertunorderedlist', '|',
            'inserttable', 'deletetable', 'mergecells', 'mergeright', 'mergedown']
        ]
      },
      rules: {
        title: [{ required: true, message: "请输入会议名称", trigger: "blur" }],
        contentType: [
          { required: true, message: "请选择内容分类", trigger: "change" },
        ],
        immsortThree: [
          { required: true, message: "请选择产品分类", trigger: "change" },
        ],
        imIndustrytwo: [
          { required: true, message: "请选择领域分类", trigger: "change" },
        ],
        StartTime: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        contentHtml: [
          { required: true, message: "请填写大会介绍", trigger: "blur" },
        ],
      },
      contentLeft:null
    };
  },
  created(){
   if (this.$route.query.meetType==2) {
    this.contentLeft={
      title:'定制厂商会',
      content:'定制研讨会为预约审核机制，审核通过后，开启会议直播'
    }
   }
  },
  mounted() {
    //从列表进来
    if (this.$route.query.mid) {
      this.getSmallMeetingInfo();
    }
    //从草稿箱进来
    if(this.$route.query.id){
      this.getDraftsMeetingInfo();
    }
  },
  methods: {
    isleave(val){
     this.isCanleave=val
    },
    getDraftsMeetingInfo(){
      this.showvideo = false;
      let form={
        id:this.$route.query.id,
        imshowId:this.$store.getters.imShowId
      }
         api.selfMeting.getMeetingDraftById(form).then(res=>{
           this.ruleForm = JSON.parse(res.data.meetinginfo);
        if (this.ruleForm.imIndustrytwo) {
          this.DomainClassification.push(Number(this.ruleForm.imIndustryone));
          this.DomainClassification.push(Number(this.ruleForm.imIndustrytwo));
        }
        if (this.ruleForm.immsortThree) {
          this.ProductClassification.push(Number(this.ruleForm.immsortOne));
          this.ProductClassification.push(Number(this.ruleForm.immsortTwo));
          this.ProductClassification.push(Number(this.ruleForm.immsortThree));
        }
        this.ruleForm.StartTime = changeDateFormat7(this.ruleForm.StartTime);
        setTimeout(() => {
          this.showvideo = true;
        }, 1000);
         })
    },
    saveDrafts(){
      let form={
        company:this.$store.state.root.companyData.webinarCompanyName,
        imshowid:this.$store.getters.imShowId,
        meettype:this.$route.query.meetType?this.$route.query.meetType:3,
        meetinginfo:JSON.stringify(this.ruleForm) 
      }
       //判断从定制厂商会进来
      if (this.$route.query.meetType) {
        form.meettype=this.$route.query.meetType
      }
     
      if(this.$route.query.id){
        form.id=this.$route.query.id
      }
      api.selfMeting.saveMeetingDraft(form).then(res=>{
        this.$message({type:'success',message:'保存成功！'})
        this.isCanleave=true
        if(this.$route.query.meetType){
          if (this.$route.query.meetType==3) {
            this.$router.push('/selfCreate/selfMeting')
          }else{
            this.$router.push('/custoMade/index')
          }
        }else{
          this.$router.push('/selfCreate/selfMeting')
        }
       
      })
    },
    changeImmsort(val) {
      this.ruleForm.immsortOne = val[0];
      this.ruleForm.immsortTwo = val[1];
      this.ruleForm.immsortThree = val[2];
      this.$nextTick(() => {
        let data = this.$refs["areaCascader"].getCheckedNodes(false);
        this.ruleForm.immsortOneName = data[0].pathLabels[0];
        this.ruleForm.immsortTwoName = data[0].pathLabels[1];
        this.ruleForm.immsortThreeName = data[0].pathLabels[2];
      });
    },
    changeImIndustry(val) {
      this.ruleForm.imIndustryone = val[0];
      this.ruleForm.imIndustrytwo = val[1];
      this.$nextTick(() => {
        let data = this.$refs["areaCascader2"].getCheckedNodes(false);
        this.ruleForm.imIndustryoneName = data[0].pathLabels[0];
        this.ruleForm.imIndustrytwoName = data[0].pathLabels[1];
      });
    },
    getSmallMeetingInfo() {
      this.showvideo = false;
      let form = {
        imshowId: this.$store.getters.imShowId,
        mid: this.$route.query.mid,
      };
      api.selfMeting.getSmallMeetingInfo(form).then((res) => {
        this.ruleForm = res.data;
        if (this.ruleForm.imIndustrytwo) {
          this.DomainClassification.push(Number(this.ruleForm.imIndustryone));
          this.DomainClassification.push(Number(this.ruleForm.imIndustrytwo));
        }
        if (this.ruleForm.immsortThree) {
          this.ProductClassification.push(Number(this.ruleForm.immsortOne));
          this.ProductClassification.push(Number(this.ruleForm.immsortTwo));
          this.ProductClassification.push(Number(this.ruleForm.immsortThree));
        }
        this.ruleForm.StartTime = changeDateFormat7(this.ruleForm.StartTime);
        setTimeout(() => {
          this.showvideo = true;
        }, 500);
        this.defaultMSGPc = this.ruleForm.contentHtml;
      });
      
    },
    editorReady(instance) {
      this.instance = instance;
      instance.setContent(this.ruleForm.contentHtml);
      instance.addListener("contentChange", () => {
        this.ruleForm.contentHtml = instance.getContent();
        this.ruleForm.content= instance.getContentTxt()
        console.log(this.ruleForm.content,'this.ruleForm.content');
        this.againValidate();
      });
    },
    againValidate() {
      this.$refs.ruleForm.validate((vaild) => {});
    },
    // 获取产品分类内容
    getLazyload(node, resolve) {
      if (!node) {
        return false;
      }
      const { level } = node;

      axios(
        `https://gateway.instrument.com.cn/classificationMonitoring/classify/getPrincipleClassifySelectByParentId?parentId=${
          level == 0 ? 0 : node.value
        }`,
        { headers: { "Content-type": "application/x-www-form-urlencoded" } }
      ).then((res) => {
        // 换成你的接口方法
        if (res.data.code == 1) {
          resolve(
            res.data.data.map((val) => {
              return {
                value: val.id,
                label: val.name,
                leaf: level >= 2, // 因为省市区三项，所以第三次点击就不用在加载了，所以 >=2
              };
            })
          );
        }
      });
    },
    // 获取领域分类内容
    getLazyload2(node, resolve) {
      if (!node) {
        return false;
      }
      const { level } = node;
      axios(
        `https://gateway.instrument.com.cn/classificationMonitoring/classify/getIndustryClassifySelectByParentId?parentId=${
          level == 0 ? 0 : node.value
        }`,
        { headers: { "Content-type": "application/x-www-form-urlencoded" } }
      ).then((res) => {
        // 换成你的接口方法
        if (res.data.code == 1) {
          resolve(
            res.data.data.map((val) => {
              return {
                value: val.id,
                label: val.name,
                leaf: level >= 1, // 因为省市区三项，所以第三次点击就不用在加载了，所以 >=2
              };
            })
          );
        }
      });
    },
    submitForm(formName) {
      const passwordValid = Cookies.get('passwordValid')
  const username = Cookies.get('username')
  const mobile = Cookies.get('mobile')
  const CheckValid = Cookies.get('CheckValid')
   if (mobile && passwordValid && username && CheckValid) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isStep2 = true;
          this.firstFrom = this.ruleForm;
        } else {
          return false;
        }
      });
    }else{
      var _this = this;
      _this.isCanleave = true;
      this.$router.push('/login?type=sign')
    }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  beforeRouteLeave:function(to, from, next){
    var _this=this
    if (_this.isCanleave) {
      next()
    } else {
      next(false)
      setTimeout(() => {
        _this.$confirm('系统可能不会保存您所做的更改。', '离开此页面？', {
          confirmButtonText: '离开',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            _this.isCanleave = true
            next()
          })
          .catch(() => {
            next(false)
            // cancelButton回调，把当前页路由推回
            // 不能使用this.$router进行路由操作，会触发beforeRouteLeave导致死循环
            window.history.pushState('', '', _this.currentUrl)
          })
      }, 300)
    }
  }
};
</script>

<style lang="scss" scoped>
.wid450 {
  width: 450px !important;
}
.formWidthdpl300 {
  width: 300px !important;
}
.wid200 {
  width: 200px !important;
}
.apply_right {
  margin-left: 16px;
  flex-grow: 1;
  width: 50%;
  background: #fff;
  .right_form {
    padding: 32px;
    border-top: 1px solid #f0f3f7;
  }
}
.apply_right2 {
  flex-grow: 1;
  width: 50%;
  background: #fff;
}
.right_btm {
  margin-top: 100px;
  padding-top: 24px;
  border-top: 1px solid #e5eaf0;
  text-align: center;
}
</style>